<template>
  <el-dialog
    v-model="visible"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    append-to-body
    class="unified-dialog batch-dialog-complex"
  >
    <template #header>
      <DialogHeader
        icon="Setting"
        title="复杂配置型批量操作示例"
        description="多阶段配置流程，包含模式选择、参数编辑、时间戳工具等"
        type="primary"
      />
    </template>
    <div class="bulk-info" v-loading="loading">
      <el-alert
        title="批量操作"
        type="warning"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>将对以下 {{ items.length }} 个项目进行操作：</p>
          <ul class="item-list">
            <li v-for="item in items" :key="item.id || item.name">
              {{ item.name || item.topic_name }}
            </li>
          </ul>
        </template>
      </el-alert>
    </div>
    
    <!-- 模式选择阶段 -->
    <div v-if="!form.modeSelected" class="mode-selection">
      <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
        label-position="left"
        style="margin-top: 20px"
      >
        <el-form-item label="操作间隔">
          <el-input-number
            v-model="form.interval"
            :min="1"
            :max="60"
            controls-position="right"
          />
          <span class="form-tip">秒，避免同时操作造成系统压力</span>
        </el-form-item>
        
        <el-form-item label="环境选择">
          <el-select
            v-model="form.environment"
            placeholder="选择环境"
            clearable
            filterable
            popper-append-to-body
            popper-class="batch-dialog-select-popper"
            style="width: 100%"
            @visible-change="handleSelectVisibleChange"
          >
            <el-option
              v-for="env in environmentOptions"
              :key="env.value"
              :label="`${env.label} (${env.host}:${env.port})`"
              :value="env.value"
            />
          </el-select>
          <span class="form-tip">选择操作环境，留空使用默认环境</span>
        </el-form-item>
        
        <el-form-item label="更新数据库">
          <el-switch
            v-model="form.update_db"
            active-text="是"
            inactive-text="否"
          />
          <span class="form-tip">多环境场景建议关闭，避免数据混乱</span>
        </el-form-item>
      </el-form>
      
      <div class="mode-description">
        <el-alert
          title="参数模式选择"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p><strong>使用默认参数：</strong>使用数据库中保存的原始参数进行操作，快速操作无需编辑参数</p>
            <p><strong>使用统一参数：</strong>为所有项目设置统一的参数，适合批量参数更新</p>
          </template>
        </el-alert>
      </div>
    </div>

    <!-- 参数编辑阶段 -->
    <div v-if="form.modeSelected && form.mode === 'unified'" class="param-editing">
      <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
        label-position="left"
        style="margin-top: 20px"
      >
        <el-form-item label="统一参数">
          <el-input
            v-model="form.unified_args"
            type="textarea"
            :rows="8"
            placeholder="输入统一的程序参数，例如：--parallelism 2 --env test --timestamp 1756958400000"
          />
          <div class="param-templates">
            <el-button size="small" @click="applyTemplate('basic')">基础参数</el-button>
            <el-button size="small" @click="applyTemplate('test')">测试环境</el-button>
            <el-button size="small" @click="applyTemplate('dev')">开发环境</el-button>
            <el-button size="small" @click="applyTemplate('timestamp')">带时间戳</el-button>
            <el-button size="small" type="primary" @click="showTimestampPicker">
              <el-icon><Clock /></el-icon>
              生成时间戳
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          v-if="!form.modeSelected" 
          type="success" 
          @click="selectMode('default')"
          class="default-mode-btn"
        >
          <el-icon><Document /></el-icon>
          使用默认参数
        </el-button>
        <el-button 
          v-if="!form.modeSelected" 
          type="primary" 
          @click="selectMode('unified')"
          class="unified-mode-btn"
        >
          <el-icon><Edit /></el-icon>
          使用统一参数
        </el-button>
        <el-button 
          v-if="form.modeSelected && form.mode === 'unified'" 
          type="primary" 
          @click="handleSubmit"
          class="confirm-btn"
        >
          <el-icon><Check /></el-icon>
          确认操作
        </el-button>
        <el-button 
          v-if="form.modeSelected && form.mode === 'default'" 
          type="success" 
          @click="handleSubmit"
          class="confirm-btn"
        >
          <el-icon><Check /></el-icon>
          确认操作
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 时间戳选择器弹窗 -->
  <el-dialog
    v-model="timestampPickerVisible"
    title="选择时间戳"
    width="500px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="timestamp-picker">
      <div class="timestamp-info-banner">
        <div class="info-icon">
          <el-icon><InfoFilled /></el-icon>
        </div>
        <div class="info-content">
          <h4 class="info-title">时间戳说明</h4>
          <p class="info-text">选择的时间将转换为毫秒时间戳并插入到参数中</p>
        </div>
      </div>
      
      <el-form label-width="100px">
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            :clearable="true"
            @change="handleDateChange"
            style="width: 100%"
            teleported
            popper-class="batch-dialog-select-popper"
          />
        </el-form-item>
        
        <el-form-item label="选择时间">
          <el-time-picker
            v-model="selectedTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
            @change="handleTimeChange"
            style="width: 100%"
            teleported
            popper-class="batch-dialog-select-popper"
          />
        </el-form-item>
        
        <el-form-item label="时间戳预览">
          <el-input
            :value="timestampPreview"
            readonly
            placeholder="选择时间后显示时间戳"
          />
        </el-form-item>
        
        <el-form-item label="参数预览">
          <el-input
            :value="paramPreview"
            type="textarea"
            :rows="3"
            readonly
            placeholder="显示插入时间戳后的完整参数"
          />
        </el-form-item>
        
        <el-form-item label="快捷选择">
          <div class="quick-select-buttons">
            <el-button size="small" @click="setQuickTime('1h')" plain>1小时前</el-button>
            <el-button size="small" @click="setQuickTime('6h')" plain>6小时前</el-button>
            <el-button size="small" @click="setQuickTime('12h')" plain>12小时前</el-button>
            <el-button size="small" @click="setQuickTime('today')" plain>今天开始</el-button>
            <el-button size="small" @click="setQuickTime('yesterday')" plain>昨天开始</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="timestampPickerVisible = false">取消</el-button>
        <el-button type="primary" @click="insertTimestamp">
          插入时间戳
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Edit, Clock, Check, InfoFilled } from '@element-plus/icons-vue'
import DialogHeader from '@/components/DialogHeader.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  items: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'success', 'start-batch'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()

// Mock 环境选项
const environmentOptions = ref([
  { label: '生产环境', value: 'prod', host: 'flink-prod.example.com', port: 8081 },
  { label: '测试环境', value: 'test', host: 'flink-test.example.com', port: 8082 },
  { label: '开发环境', value: 'dev', host: 'flink-dev.example.com', port: 8083 }
])

const form = ref({
  mode: '',
  modeSelected: false,
  unified_args: '',
  interval: 5,
  environment: '',
  update_db: false
})

const handleSelectVisibleChange = (visible) => {
  const poppers = document.querySelectorAll('.batch-dialog-select-popper')
  console.log('[BatchDialogComplex] select visible ->', visible)
  console.log('[BatchDialogComplex] current poppers ->', poppers)
  poppers.forEach((popper, index) => {
    const styles = window.getComputedStyle(popper)
    console.log('[BatchDialogComplex] popper info', index, {
      display: styles.display,
      opacity: styles.opacity,
      visibility: styles.visibility,
      zIndex: styles.zIndex,
      pointerEvents: styles.pointerEvents,
      top: styles.top,
      left: styles.left
    })
  })
}

// 时间戳选择器相关状态
const timestampPickerVisible = ref(false)
const selectedDate = ref('')
const selectedTime = ref('')

// 日期快捷选择配置
const dateShortcuts = [
  {
    text: '今天',
    value: () => new Date()
  },
  {
    text: '明天',
    value: () => {
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      return tomorrow
    }
  },
  {
    text: '后天',
    value: () => {
      const dayAfterTomorrow = new Date()
      dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)
      return dayAfterTomorrow
    }
  }
]

const handleClose = () => {
  visible.value = false
}

const initForm = () => {
  form.value = {
    mode: '',
    modeSelected: false,
    unified_args: '',
    interval: 5,
    environment: '',
    update_db: false
  }
}

// 模式选择
const selectMode = (mode) => {
  form.value.mode = mode
  form.value.modeSelected = true
}

// 参数模板
const paramTemplates = {
  basic: '--parallelism 1 --env dev',
  test: '--parallelism 2 --env test',
  dev: '--parallelism 1 --env dev',
  timestamp: `--parallelism 1 --env test --timestamp ${Date.now()}`
}

const applyTemplate = (templateKey) => {
  const template = paramTemplates[templateKey]
  if (template) {
    form.value.unified_args = template
    ElMessage.success(`已应用${templateKey}参数模板`)
  }
}

// 时间戳相关计算属性
const timestampPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  return timestamp.toString()
})

const paramPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.unified_args.trim()
  if (!currentArgs) {
    return timestampStr
  }
  
  if (currentArgs.includes('--timestamp')) {
    return currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
  } else {
    return currentArgs + ' ' + timestampStr
  }
})

// 显示时间戳选择器
const showTimestampPicker = () => {
  const now = new Date()
  selectedDate.value = now.toISOString().slice(0, 10)
  selectedTime.value = now.toTimeString().slice(0, 8)
  timestampPickerVisible.value = true
}

// 处理日期变化
const handleDateChange = (value) => {
  if (value) {
    // 日期变化处理
  }
}

// 处理时间变化
const handleTimeChange = (value) => {
  if (value) {
    // 时间变化处理
  }
}

// 快捷时间选择
const setQuickTime = (type) => {
  const now = new Date()
  let targetTime
  
  switch (type) {
    case '1h':
      targetTime = new Date(now.getTime() - 1 * 60 * 60 * 1000)
      break
    case '6h':
      targetTime = new Date(now.getTime() - 6 * 60 * 60 * 1000)
      break
    case '12h':
      targetTime = new Date(now.getTime() - 12 * 60 * 60 * 1000)
      break
    case 'today':
      targetTime = new Date(now)
      targetTime.setHours(0, 0, 0, 0)
      break
    case 'yesterday':
      targetTime = new Date(now)
      targetTime.setDate(now.getDate() - 1)
      targetTime.setHours(0, 0, 0, 0)
      break
    default:
      targetTime = now
  }
  
  selectedDate.value = targetTime.toISOString().split('T')[0]
  selectedTime.value = targetTime.toTimeString().split(' ')[0]
  
  const labels = {
    '1h': '1小时前',
    '6h': '6小时前',
    '12h': '12小时前',
    'today': '今天开始',
    'yesterday': '昨天开始'
  }
  ElMessage.success(`已设置为${labels[type] || '未知'}`)
}

// 插入时间戳
const insertTimestamp = () => {
  if (!selectedDate.value || !selectedTime.value) {
    ElMessage.warning('请先选择日期和时间')
    return
  }
  
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.unified_args.trim()
  if (!currentArgs) {
    form.value.unified_args = timestampStr
  } else {
    if (currentArgs.includes('--timestamp')) {
      form.value.unified_args = currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
    } else {
      form.value.unified_args = currentArgs + ' ' + timestampStr
    }
  }
  
  timestampPickerVisible.value = false
  ElMessage.success(`已插入时间戳: ${timestamp}`)
}

const handleSubmit = () => {
  handleClose()
  
  const batchParams = {
    mode: form.value.mode,
    interval: form.value.interval,
    environment: form.value.environment || undefined,
    update_db: form.value.update_db
  }
  
  if (form.value.mode === 'unified') {
    batchParams.unified_args = form.value.unified_args || ''
  }
  
  emit('start-batch', {
    items: props.items,
    params: batchParams
  })
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})
</script>

<style scoped>
.bulk-info {
  margin-bottom: 20px;
}

.item-list {
  margin: 10px 0 0 0;
  padding-left: 20px;
  max-height: 150px;
  overflow-y: auto;
}

.item-list li {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

.mode-description {
  margin-bottom: 20px;
}

.mode-description :deep(.el-alert__content) {
  line-height: 1.6;
}

.mode-description p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.param-templates {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.param-templates .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
}

.form-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.timestamp-picker {
  padding: 10px 0;
}

.timestamp-info-banner {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px 20px;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #e0f2fe 0%, #dbeafe 100%);
  border-left: 4px solid #0284c7;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(2, 132, 199, 0.1);
  transition: all 0.3s ease;
}

.timestamp-info-banner:hover {
  box-shadow: 0 4px 16px rgba(2, 132, 199, 0.15);
  transform: translateY(-1px);
}

.info-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
  border-radius: 50%;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(2, 132, 199, 0.3);
}

.info-icon .el-icon {
  font-size: 24px;
  color: #ffffff;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #0c4a6e;
  line-height: 1.4;
}

.info-text {
  margin: 0;
  font-size: 14px;
  color: #075985;
  line-height: 1.6;
}

.timestamp-picker .el-form-item {
  margin-bottom: 20px;
}

.timestamp-picker :deep(.el-input[readonly] .el-input__wrapper),
.timestamp-picker :deep(.el-textarea[readonly] .el-textarea__inner) {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
  color: #0369a1;
  font-weight: 500;
  cursor: default;
  box-shadow: 0 2px 8px rgba(3, 105, 161, 0.08);
}

.timestamp-picker :deep(.el-input[readonly] .el-input__inner) {
  color: #0369a1;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
}

.timestamp-picker :deep(.el-textarea[readonly] .el-textarea__inner) {
  color: #0369a1;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  line-height: 1.6;
}

.default-mode-btn {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
  font-weight: 500;
  min-width: 160px;
}

.default-mode-btn:hover {
  background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%) !important;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
}

.unified-mode-btn {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  font-weight: 500;
  min-width: 160px;
}

.unified-mode-btn:hover {
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%) !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
}

.confirm-btn {
  font-weight: 600;
  min-width: 120px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.quick-select-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-select-buttons .el-button {
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 13px;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
}

.quick-select-buttons .el-button:hover {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: #409eff;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.quick-select-buttons .el-button:active {
  transform: translateY(0);
}
</style>

